package services

import (
	"fmt"
	"image/jpeg"
	"image/png"
	"longmen/server/config/global"
	"math/rand"
	"os"
	"strconv"
	"time"

	"github.com/wind-2019/captcha"
	"longmen/server/pkg/common/api_models"
)

func Check(id string, left int) bool {
	val, err := global.GetRds().Get("captcha" + id).Result()

	if val == "" || err != nil {
		return false
	}

	val2int, _ := strconv.Atoi(val)

	return ((val2int-left) < 10 && (val2int-left) >= -10)
}

func GetCaptchaImage(imgPath string) *api_models.CaptchaResp {
	cap := captcha.New()
	n := strconv.Itoa(rand.Intn(7) + 10)
	if err := cap.SetBgImg(imgPath + n + ".jpg"); err != nil {
		return nil
	}
	if err := cap.SetBgImgLayer(imgPath + "/hycdn.png"); err != nil {
		return nil
	}
	_, im, slide := cap.OutImgEncodeString()
	x, y := cap.GetXY()
	id := time.Now().Format("150405") + strconv.Itoa(y)
	global.GetRds().Set("captcha"+id, x, 300*time.Second)

	return &api_models.CaptchaResp{
		ID: id,
		// X:     x,
		Y:     y,
		Image: im,
		Slide: slide,
	}
}

func GetCaptchaImagePath(imgPath string) (*api_models.CaptchaResp, error) {
	cap := captcha.New()
	n := strconv.Itoa(rand.Intn(7) + 10)
	if err := cap.SetBgImg(imgPath + n + ".jpg"); err != nil {
		global.Log.Errorf("err:%v", err)
		return nil, err
	}
	if err := cap.SetBgImgLayer(imgPath + "hycdn.png"); err != nil {
		global.Log.Errorf("err:%v", err)
		return nil, err
	}

	image, slideImage := cap.OutImg()

	var outFile *os.File
	var outFile1 *os.File
	var err error
	var dir = "/var/www/captcha/"

	imageName := time.Now().Format("2006-01-02") + "-i-" + fmt.Sprintf("%d", time.Now().UnixMilli()) + ".jpg"
	slideName := time.Now().Format("2006-01-02") + "-s-" + fmt.Sprintf("%d", time.Now().UnixMilli()) + ".png"
	if outFile, err = os.Create(dir + imageName); err != nil {
		global.Log.Debugf("imageName Create error %+v:", err)
		return nil, err
	}

	if err = jpeg.Encode(outFile, image, &jpeg.Options{Quality: 80}); err != nil {
		global.Log.Debugf("imageName Encode error %+v:", err)
		return nil, err
	}

	if outFile1, err = os.Create(dir + slideName); err != nil {
		global.Log.Debugf("slideName Create error %+v:", err)
		return nil, err
	}

	if err = png.Encode(outFile1, slideImage); err != nil {
		global.Log.Debugf("slideName Encode error %+v:", err)
		return nil, err
	}

	// _, im, slide := cap.OutImgEncodeString()
	x, y := cap.GetXY()
	id := time.Now().Format("150405") + strconv.Itoa(y)
	global.GetRds().Set("captcha"+id, x, 300*time.Second)

	go func() {
		time.Sleep(60 * time.Second)
		os.Remove(dir + imageName)
		os.Remove(dir + slideName)
	}()

	return &api_models.CaptchaResp{
		ID: id,
		// X:     x,
		Y:     y,
		Image: imageName,
		Slide: slideName,
	}, nil
}
